package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    // {"success" : true, "msg" :"登录成功"}
    // {"success" : false, "msg" :"登录失败"}
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {
        Employee employee = employeeService.login(username, password);
        if (employee != null) {
            // 往 session 存入登录员工对象
            UserContext.setEmployee(employee);
            if (!employee.isAdmin()) { // 不是管理员, 为了性能
                List<String> expressions = permissionService.queryExpressionsByEmployeeId(employee.getId());
                UserContext.setExpressions(expressions);
            }

            return new JsonResult(true, "登录成功");
        } else {
            return new JsonResult(false, "登录失败");
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        HttpSession session = UserContext.getSession();
        session.invalidate();
        // 跳转到登录页面
        return "redirect:/static/login.html";
    }

    // 访问没有权限页面
    @RequestMapping("/nopermission")
    public String nopermission() {
        return "common/nopermission";
    }
}
